using System;

namespace Axe.Geometry
{
	/// <summary>
	/// Summary description for Quads.
	/// </summary>
	public class Quad
	{
		public Vector3 TLeft;
		public Vector3 BLeft;
		public Vector3 TRight;
		public Vector3 BRight;

		public Vector3 TLeftNormal;
		public Vector3 BLeftNormal;
		public Vector3 TRightNormal;
		public Vector3 BRightNormal;

		public Vector3 this[int index]
		{
			get
			{
				switch(index)
				{
					case 0: return TLeft;
					case 1: return BLeft;
					case 2: return BRight;
					case 3: return TRight;
					default: throw new IndexOutOfRangeException();
				}
			}
		}

		public void CalcNormals()
		{
			Vector3 main = new Vector3();
			Vector3 p1 = new Vector3();
			Vector3 p2 = new Vector3();
			Vector3 normal = new Vector3();

			main.Set(TLeft);
			p1.Set(BLeft);
			p2.Set(TRight);
			p1.Subtract(main);
			p2.Subtract(main);
			normal = Vector3.Cross(p1,p2);
			normal.Normalize();
			normal.Invert();
			TLeftNormal.Set(normal);

			main.Set(BLeft);
			p1.Set(BRight);
			p2.Set(TLeft);
			p1.Subtract(main);
			p2.Subtract(main);
			normal = Vector3.Cross(p1,p2);
			normal.Normalize();
			normal.Invert();
			BLeft.Set(normal);

			main.Set(BRight);
			p1.Set(TRight);
			p2.Set(BLeft);
			p1.Subtract(main);
			p2.Subtract(main);
			normal = Vector3.Cross(p1,p2);
			normal.Normalize();
			normal.Invert();
			BRightNormal.Set(normal);

			main.Set(TRight);
			p1.Set(TLeft);
			p2.Set(BRight);
			p1.Subtract(main);
			p2.Subtract(main);
			normal = Vector3.Cross(p1,p2);
			normal.Normalize();
			normal.Invert();
			TRightNormal.Set(normal);

		}

		public Vector3 CenterPoint
		{
			get
			{
				return Quad.GetCenterPoint(this);
			}
		}

		public static Vector3 GetCenterPoint(Quad q)
		{
			Vector3 TMid = new Vector3();
			TMid.Add(q.TLeft);
			TMid.Add(q.TRight);
			TMid.Divide(2.0);
			Vector3 BMid = new Vector3();
			BMid.Add(q.BLeft);
			BMid.Add(q.BRight);
			BMid.Divide(2.0);
			Vector3 Mid = new Vector3();
			Mid.Add(TMid);
			Mid.Add(BMid);
			Mid.Divide(2.0);
			return Mid;
		}

		public static Vector3 GetCenterPoint(Vector3 tl,Vector3 tr,Vector3 bl,Vector3 br)
		{
			Vector3 TMid = new Vector3();
			TMid.Add(tl);
			TMid.Add(tr);
			TMid.Divide(2.0);
			Vector3 BMid = new Vector3();
			BMid.Add(bl);
			BMid.Add(br);
			BMid.Divide(2.0);
			Vector3 Mid = new Vector3();
			Mid.Add(TMid);
			Mid.Add(BMid);
			Mid.Divide(2.0);
			return Mid;
		}

		public Quad()
		{
			TLeft = new Vector3();
			BLeft = new Vector3();
			TRight = new Vector3();
			BRight = new Vector3();

			TLeftNormal = new Vector3();
			BLeftNormal = new Vector3();
			TRightNormal = new Vector3();
			BRightNormal = new Vector3();
		}
	}
}
